package com.byedu.course;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

import com.byedu.domain.course.vo.*;
import com.byedu.domain.course.*;
import com.byedu.mapper.course.*;
import com.byedu.model.constants.APIConstants;
import com.byedu.parser.LibraryExcelParser;
import com.byedu.util.ArrayUtil;

import com.byedu.util.CommonUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.byedu.base.BaseService;
import com.byedu.model.exception.ApiException;
import com.byedu.model.exception.course.QuestionNotFoundException;
import com.byedu.util.Constants;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by weidangwang on 2017/4/23.
 */
@Service
public class QuestionService extends BaseService{


    private final LibraryExcelParser libraryExcelParser = new LibraryExcelParser();
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private AnswerMapper answerMapper;

    @Autowired
    private UserQuestionErrMapper userQuestionErrMapper;

    @Autowired
    private UserQuestionMapper userQuestionMapper;
    @Autowired
    private UserCourseMapper userCourseMapper;
    @Autowired
    private LibraryMapper libraryMapper;
    @Autowired
    private UserLibraryMapper userLibraryMapper;

    @Autowired
    private LibQuestionTempMapper libQuestionTempMapper;

    public Integer getQuestionMaxId(){
        return questionMapper.getQuestionMaxId();
    }

   public int bathcInsertQuestionDOList(List<QuestionDO> questionDOList) {
      return questionMapper.insertQuestionDOList(questionDOList);
    }

    /**
     * 导入题库
     * @author luo
     * @date 2017-04-28
     * @param questionVO
     * @return
     */
    public int insertQuestion(QuestionVO questionVO) throws InvocationTargetException, IllegalAccessException {
        List<AnswerVO> answerVOList = questionVO.getAnswers();
        QuestionDO questionDO = new QuestionDO();
        BeanUtils.copyProperties(questionDO, questionVO);
        int returnInt = questionMapper.insertQuestion(questionDO);

        if(returnInt==1) {
            for (int i = 0; i < answerVOList.size(); i++) {
                AnswerDO answerDO = new AnswerDO();
                BeanUtils.copyProperties(answerDO,answerVOList.get(i));
                int anInt=answerMapper.insertAnswer(answerDO);
                if (anInt==0){
                    throw new QuestionNotFoundException();//抛出异常
                }
            }
        }
        
        return returnInt;

    }
    /**
     * @description 获取专题下面的考题集
     * @author chenxigui
     * @date 2017-04-26
     * @param libraryId
     * @return
     */
    public List<QuestionVO> listQuestionsByLibraryId(Integer libraryId) {
        List<QuestionDO> questionDOList = questionMapper.listQuestionsByLibraryId(libraryId);
        return convertToQuestionVOList(questionDOList);
    }

    public List<QuestionOnlyVO> listQuestionOnlysByLibraryId(Integer libraryId) {
        List<QuestionDO> questionDOList = questionMapper.listQuestionsByLibraryId(libraryId);
        return convertToQuestionOnlyVOList(questionDOList);
    }

    public List<QuestionVO> listQuestions() {
        List<QuestionDO> questionDOList = questionMapper.listQuestions();
        return convertToQuestionVOList(questionDOList);
    }
    public List<QuestionVO> convertToQuestionVOList( List<QuestionDO> questionDOList) {
        List<QuestionVO> questionVOList = new ArrayList<QuestionVO>();
        if(questionDOList!=null && questionDOList.size()>0) {
            int no = 1 ;
            for (QuestionDO questionDO : questionDOList) {

                QuestionVO questionVO = new QuestionVO(questionDO, null);
                questionVO.setNo(no);
                no++;
                questionVOList.add(questionVO);
            }
        }
        return questionVOList;
    }

    public List<QuestionOnlyVO> convertToQuestionOnlyVOList( List<QuestionDO> questionDOList) {
        List<QuestionOnlyVO> questionVOList = new ArrayList<QuestionOnlyVO>();
        for (QuestionDO questionDO : questionDOList) {

            QuestionOnlyVO questionVO = new QuestionOnlyVO(questionDO,null);

            questionVOList.add(questionVO);
        }

        return questionVOList;
    }
    public List<QuestionVO> dealQuestionSequence(List<QuestionVO> questionVOList) {
        int sequence = 0;
        for (QuestionVO questionVO : questionVOList) {
            questionVO.setNo(++sequence);
        }

        return questionVOList;
    }



    /**
     * @description 获取用户所购买课程下专题对应的仅仅做题
     * @author chenxigui
     * @date 2017-04-26
     * @param libraryId
     * @param userId
     * @return
     */
    public List<QuestionVO> listQuestions(Integer libraryId, String userId) {
        //1.查看用户是否购买
        if (libraryId != null) {
            try {
                //1.获取用户所购买课程下专题对应的考题集
                List<QuestionVO> questionVOList = listQuestionsByLibraryId(libraryId);
                List<Integer> questionIds = listQuestionIds(questionVOList);
                //2.获取考题集对应的答案，即对应的选项集
                List<AnswerDO> answerDOList = answerMapper.listAnwsersByQuestionIds(questionIds);
                //3.将Answer的集合封装到对应的考题中
                fillAnswersIntoQuestions(questionVOList, answerDOList);
                if (CollectionUtils.isNotEmpty(questionVOList)) {
                    Collections.sort(questionVOList, new Comparator<QuestionVO>() {
                        @Override
                        public int compare(QuestionVO vo1, QuestionVO vo2) {
                            return vo1.getNo() - vo2.getNo();
                        }
                    });
                }

                LibraryDO libraryDO = libraryMapper.getLibraryDOById(libraryId);
                if (StringUtils.isNotEmpty(userId)) {
                    int count = userCourseMapper.countUserCourses(userId, String.valueOf(libraryDO.getCourseId()));
                    if (count > 0) {
                        //用户已购买该课程
                        return questionVOList;
                    }
                }

                //用户未购买该课程或者用户未登录  此时用户只能看到试用的题目
                int trialNum = libraryDO.getTrialNum();
                if (trialNum > 0) {
                    int size = questionVOList.size();
                    if (size > trialNum) {
                        return questionVOList.subList(0, trialNum);
                    } else {
                        libraryDO.setTrialNum(size);
                        return questionVOList;
                    }
                } else {
                    //未启用试用
                    return  new ArrayList<QuestionVO>();
                }

            } catch (ApiException e) {
                logger.info("获取考题信息异常！{}", e);
            }
        }

        return null;
    }


    public List<QuestionVO> listQuestionsByErrorId(String userId,Integer courseId) {
        List<Integer> userQuestionErrDOList = userQuestionErrMapper.listErrIdsByUserId(userId);
        HashMap <String,Object> map=new HashMap<String,Object>();
        map.put("courseId",courseId);
        map.put("questionIds",userQuestionErrDOList);
        System.out.println("----"+userQuestionErrDOList.toString());
        List<QuestionDO> questionDOList = questionMapper.listQuestionsByCourseIdQuestionId(map);


        return convertToQuestionVOList(questionDOList);
    }
    /**
     * @description 获取用户所购买课程下专题对应的仅仅做题
     * @author chenxigui
     * @date 2017-04-26
     * @param courseId
     * @param userId
     * @return
     */
    public List<QuestionVO> listErrQuestions( String userId,Integer courseId) {
        //1.查看用户是否购买
            try {
                //1.获取用户所购买课程下专题对应的考题集

                List<QuestionVO> questionVOList = listQuestionsByErrorId(userId,courseId);
                if(questionVOList == null || questionVOList.size() ==0 ){
                    return new ArrayList<QuestionVO>();
                }
                List<Integer> questionIds = listQuestionIds(questionVOList);
                //2.获取考题集对应的答案，即对应的选项集
                List<AnswerDO> answerDOList = answerMapper.listAnwsersByQuestionIds(questionIds);
                //3.将Answer的集合封装到对应的考题中
                fillAnswersIntoQuestions(questionVOList, answerDOList);
                if (CollectionUtils.isNotEmpty(questionVOList)) {
                    Collections.sort(questionVOList, new Comparator<QuestionVO>() {
                        @Override
                        public int compare(QuestionVO vo1, QuestionVO vo2) {
                            return vo1.getNo() - vo2.getNo();
                        }
                    });
                }


                //用户未购买该课程或者用户未登录  此时用户只能看到试用的题目
                return questionVOList;

            } catch (ApiException e) {
                logger.info("获取考题信息异常！{}", e);
            }

        return null;
    }



    /**
     * @description 获取用户所购买课程下专题对应的仅仅做题
     * @author luohongzhou
     * @date 2017-08-10
     * @param libraryId
     * @param userId
     * @return
     */
    public List<QuestionVO> listNewQuestions(Integer libraryId, String userId) {


        if (libraryId != null) {
            LibraryDO libraryDO = libraryMapper.getLibraryDOById(libraryId);
            //1.查看用户是否购买，
            int count = 0;
            if (StringUtils.isNotEmpty(userId)) {
                count = userCourseMapper.countUserCourses(userId, String.valueOf(libraryDO.getCourseId()));
            }
            if (count == 0) {
                UserLibraryDO userLibraryDO = userLibraryMapper.getUserLibrarybyUserIdAndLibrary(userId, libraryId);
                //2.如果没有购买
                //（2）已经答过题，返回null
                if(userLibraryDO!=null){
                    return  new ArrayList<QuestionVO>();
                }
            }

            try {
                //1.获取用户所购买课程下专题对应的考题集
                List<QuestionVO> questionVOList = listQuestionsByLibraryId(libraryId);
                List<Integer> questionIds = listQuestionIds(questionVOList);
                //2.获取考题集对应的答案，即对应的选项集
                List<AnswerDO> answerDOList = answerMapper.listAnwsersByQuestionIds(questionIds);
                //3.将Answer的集合封装到对应的考题中
                fillAnswersIntoQuestions(questionVOList, answerDOList);
                if (CollectionUtils.isNotEmpty(questionVOList)) {
                    Collections.sort(questionVOList, new Comparator<QuestionVO>() {
                        @Override
                        public int compare(QuestionVO vo1, QuestionVO vo2) {
                            return vo1.getNo() - vo2.getNo();
                        }
                    });
                }
                if (count > 0) {
                    //用户已购买该课程,返回所有题目
                    return questionVOList;
                }


               //2.如果没有购买（1）判断用户没有答题过该试卷，返回TrialNum对应的数量
                int trialNum = libraryDO.getTrialNum();
                if (trialNum > 0) {
                    int size = questionVOList.size();
                    if (size > trialNum) {
                        return questionVOList.subList(0, trialNum);
                    } else {
                        return questionVOList;
                    }
                } else {
                    //未启用试用
                    return  new ArrayList<QuestionVO>();
                }

            } catch (ApiException e) {
                logger.info("获取考题信息异常！{}", e);
            }
        }

        return null;
    }


    /**
     * @description 获取用户所购买课程下专题对应的考题集
     * @author chenxigui
     * @date 2017-04-26
     * @param libraryId
     * @param userId
     * @return
     */
    public List<QuestionOnlyVO> listQuestionOnlys(Integer libraryId, String userId) {
        if (libraryId != null) {
            try {
                //1.获取用户所购买课程下专题对应的考题集
                List<QuestionOnlyVO> questionVOList = listQuestionOnlysByLibraryId(libraryId);
                List<Integer> questionIds = listQuestionOnlyIds(questionVOList);
                //2.获取考题集对应的答案，即对应的选项集
                List<AnswerDO> answerDOList = answerMapper.listAnwsersByQuestionIds(questionIds);
                //3.将Answer的集合封装到对应的考题中
                fillAnswersIntoQuestionOnlys(questionVOList, answerDOList);
                if (CollectionUtils.isNotEmpty(questionVOList)) {
                    Collections.sort(questionVOList, new Comparator<QuestionOnlyVO>() {
                        @Override
                        public int compare(QuestionOnlyVO vo1, QuestionOnlyVO vo2) {
                            return vo1.getNo() - vo2.getNo();
                        }
                    });
                }

                LibraryDO libraryDO = libraryMapper.getLibraryDOById(libraryId);
                if (StringUtils.isNotEmpty(userId)) {
                    int count = userCourseMapper.countUserCourses(userId, String.valueOf(libraryDO.getCourseId()));
                    if (count > 0) {
                        //用户已购买该课程
                        return questionVOList;
                    }
                }

                //用户未购买该课程或者用户未登录  此时用户只能看到试用的题目
                int trialNum = libraryDO.getTrialNum();
                if (trialNum > 0) {
                    int size = questionVOList.size();
                    if (size > trialNum) {
                        return questionVOList.subList(0, trialNum);
                    } else {
                        return questionVOList;
                    }
                } else {
                    //未启用试用
                    return  new ArrayList<QuestionOnlyVO>();
                }

            } catch (ApiException e) {
            	logger.info("获取考题信息异常！{}", e);
            }
        }

        return null;
    }



    /**
     * @param questions
     * @return
     * @throws ApiException
     * @description 获取考题编号
     * @author chenxigui
     * @date 2017-04-27
     */
    public List<Integer> listQuestionOnlyIds(List<QuestionOnlyVO> questions) throws ApiException {
        List<Integer> questionIds = null;
        if (CollectionUtils.isNotEmpty(questions)) {
            questionIds = new ArrayList<Integer>();
            for (QuestionOnlyVO question : questions) {
                questionIds.add(question.getId());
            }
        } else {
            throw new ApiException();
        }

        return questionIds;
    }
    /**
     * @param questions
     * @return
     * @throws ApiException
     * @description 获取考题编号
     * @author chenxigui
     * @date 2017-04-27
     */
    public List<Integer> listQuestionIds(List<QuestionVO> questions) throws ApiException {
        List<Integer> questionIds = null;
        if (CollectionUtils.isNotEmpty(questions)) {
            questionIds = new ArrayList<Integer>();
            for (QuestionVO question : questions) {
                questionIds.add(question.getId());
            }
        } else {
            throw new ApiException();
        }

        return questionIds;
    }

    /**
     * @description 将Answer的集合封装到对应的考题中
     * @author chenxigui
     * @date 2017-04-27
     * @param questionVOList
     * @param answerDOList
     */
    public void fillAnswersIntoQuestions(List<QuestionVO> questionVOList, List<AnswerDO> answerDOList) {
        if (CollectionUtils.isNotEmpty(questionVOList) && CollectionUtils.isNotEmpty(answerDOList)) {
            /*
             * 由于answers集合中的元素已按照questionId排序，因此用fromIndex来记录记录当前循环终止的位置，
             * 也就是下一次循环开始的位置，避免重复遍历answers中的元素
             */
            int fromIndex = 0;
            int endIndex = answerDOList.size();

            for (QuestionVO questionVO : questionVOList) {
                List<AnswerVO> answerVOs = new ArrayList<AnswerVO>();
                for (AnswerDO answerDO  : answerDOList.subList(fromIndex, endIndex)) {
                    if (questionVO.getId() == answerDO.getQuestionId()) {
                        AnswerVO answerVO = new AnswerVO(answerDO);
                        answerVOs.add(answerVO);
                        fromIndex++;
                    } else {
                        break;
                    }
                }

                questionVO.setAnswers(answerVOs);
                String rightStr="";
                for(AnswerVO answerVO : answerVOs){

                    if(answerVO.isCorrect()){
                        rightStr =rightStr+answerVO.getSubOption();
                    }

                }
                questionVO.setRight(rightStr);
            }


        }
    }

    /**
     * @description 将Answer的集合封装到对应的考题中
     * @author chenxigui
     * @date 2017-04-27
     * @param questionVOList
     * @param answerDOList
     */
    public void fillAnswersIntoQuestionOnlys(List<QuestionOnlyVO> questionVOList, List<AnswerDO> answerDOList) {
        if (CollectionUtils.isNotEmpty(questionVOList) && CollectionUtils.isNotEmpty(answerDOList)) {
            /*
             * 由于answers集合中的元素已按照questionId排序，因此用fromIndex来记录记录当前循环终止的位置，
             * 也就是下一次循环开始的位置，避免重复遍历answers中的元素
             */
            int fromIndex = 0;
            int endIndex = answerDOList.size();

            for (QuestionOnlyVO questionVO : questionVOList) {
                List<AnswerOnlyVO> answerVOs = new ArrayList<AnswerOnlyVO>();
                for (AnswerDO answerDO  : answerDOList.subList(fromIndex, endIndex)) {
                    if (questionVO.getId() == answerDO.getQuestionId()) {
                        AnswerOnlyVO answerOnlyVO = new AnswerOnlyVO(answerDO, false);
                        answerVOs.add(answerOnlyVO);
                        fromIndex++;
                    } else {
                        break;
                    }
                }

                questionVO.setAnswers(answerVOs);
            }
        }
    }


    public Map<String,List<AnswerVO>> validateAnwerChecked(List<AnswerDO> answerDOList, List<UserQuestionDO> userQuestionDOList) {
        Map<String,List<AnswerVO>> map = new HashMap<String,List<AnswerVO>>();
        if (CollectionUtils.isNotEmpty(answerDOList) && CollectionUtils.isNotEmpty(userQuestionDOList)) {
            int fromIndex = 0;
            int endIndex = answerDOList.size();
            for (UserQuestionDO userQuestionDO : userQuestionDOList) {
                List<AnswerVO> answerVOList = new ArrayList<AnswerVO>();
                for (AnswerDO answerDO : answerDOList.subList(fromIndex, endIndex)) {
                    if (userQuestionDO.getQuestionId() == answerDO.getQuestionId()) {

                        AnswerVO answerVO = new AnswerVO(answerDO);
                        answerVOList.add(answerVO);
                        fromIndex++;
                    } else {
                        break;
                    }
                }

                map.put(userQuestionDO.getQuestionId()+"", answerVOList);
            }
        }

        return map;
    }

//    public Map<String,List<AnswerVO>> validateAnwerChecked(List<AnswerDO> answerDOList, List<UserQuestionDO> userQuestionDOList) {
//        Map<String,List<AnswerVO>> map = new HashMap<String,List<AnswerVO>>();
//        if (CollectionUtils.isNotEmpty(answerDOList) && CollectionUtils.isNotEmpty(userQuestionDOList)) {
//                int fromIndex = 0;
//                int endIndex = answerDOList.size();
//                for (UserQuestionDO userQuestionDO : userQuestionDOList) {
//                    List<AnswerVO> answerVOList = new ArrayList<AnswerVO>();
//                    for (AnswerDO answerDO : answerDOList.subList(fromIndex, endIndex)) {
//                        if (userQuestionDO.getQuestionId() == answerDO.getQuestionId()) {
//                            boolean checked = false;
//                            if (userQuestionDO.getSubOption().equals(answerDO.getSubOption())) {
//                                checked = true;
//                            }
//
//                            AnswerVO answerVO = new AnswerVO(answerDO, checked);
//                            answerVOList.add(answerVO);
//                            fromIndex++;
//                        } else {
//                            break;
//                        }
//                    }
//
//                    map.put(userQuestionDO.getQuestionId()+"", answerVOList);
//                }
//        }
//
//        return map;
//    }

    /**
     * @description 获取用户所购买课程下专题对应的考题集
     * @author chenxigui
     * @date 2017-05-27
     * @param userId
     * @param modeFlag
     * @return
     */
    public List<QuestionVO> listQuestions(String userId, boolean modeFlag) {
        if (userId != null) {
            try {
                //1.获取用户答题卡信息
                List<UserQuestionDO> userQuestionDOList = userQuestionMapper.listUserQuestionsByUserId(userId);
                if (CollectionUtils.isNotEmpty(userQuestionDOList)) {
                    List<Integer> questionIds = new ArrayList<Integer>();
                    for (UserQuestionDO userQuestionDO : userQuestionDOList) {
                        questionIds.add(userQuestionDO.getQuestionId());
                    }
                    //2.根据题号批量查询考题信息
                    List<QuestionDO> questionDOList = questionMapper.listQuestionsByIds(questionIds);
                    List<QuestionVO> questionVOList =convertToQuestionVOList(questionDOList);
                    //3.根据题号批量查询选项集
                    List<AnswerDO> answerDOList = answerMapper.listAnwsersByQuestionIds(questionIds);
                    //4.配置用户答题情况
                    Map<String,List<AnswerVO>> map = validateAnwerChecked(answerDOList, userQuestionDOList);
                    //5.将Answer的集合封装到对应的考题中
                    return fillAnswersIntoQuestions(questionVOList, map, modeFlag);
                }
            } catch (ApiException e) {
                logger.info("获取考题信息异常！{}", e);
            }
        }

        return null;
    }

    /**
     * @description 将Answer的集合封装到对应的考题中
     * @author chenxigui
     * @date 2017-05-29
     * @param questionVOList
     * @param map
     * @param modeFlag
     */
    public List<QuestionVO> fillAnswersIntoQuestions(List<QuestionVO> questionVOList, Map<String,List<AnswerVO>> map, boolean modeFlag) {
        List<QuestionVO> tempQuestionVOList = new ArrayList<QuestionVO>();
        if (CollectionUtils.isNotEmpty(questionVOList) && map != null && map.size() > 0) {
            for (QuestionVO questionVO : questionVOList) {
                List<AnswerVO> answerVOList = map.get(questionVO.getId()+"");
                /*如果是多选题，则所有用户选项都与标准答案一致时，才算用户答对*/
                List<Boolean> booleanList = new ArrayList<Boolean>();
                for (int i=0; i < answerVOList.size(); i++) {
                    AnswerVO answerVO = answerVOList.get(i);
                    if (answerVO.isChecked() && answerVO.isCorrect() || !answerVO.isChecked()) {
                        booleanList.add(Boolean.TRUE);
                    }

                    if (answerVO.isChecked() && !answerVO.isCorrect()) {
                        booleanList.add(Boolean.FALSE);
                    }
                }


                questionVO.setAnswers(answerVOList);
                boolean flag = ArrayUtil.and(booleanList);
                if ((modeFlag && flag) || (!modeFlag && !flag)) {
                    tempQuestionVOList.add(questionVO);
                }
            }
        }

        return tempQuestionVOList;
    }

    /**
     * 解析多个文件列表
     * @param listStr
     * @param libraryDO
     */
    @Transactional
    public void analyzeFlieQuestions(List<String> listStr, LibraryDO libraryDO) {
        //  记录上传日志，第几次上传
        Integer maxid =CommonUtil.nullInt(libQuestionTempMapper.selectMaxindexId());
        for (int i=0;i<listStr.size();i++) {
            File innerFile = new File(listStr.get(i));
            if (innerFile.exists() && innerFile.isFile()) {
                analyFile(innerFile, libraryDO, maxid);
            }
        }

    }

    /**
     * 解析单个Excel文件
     * @param dir
     * @param libraryDO
     */
    @Transactional
    public void analyzeQuestion(File dir, LibraryDO libraryDO) {
        //  记录上传日志，第几次上传
        Integer maxid =CommonUtil.nullInt(libQuestionTempMapper.selectMaxindexId());
//        if (dir != null && dir.exists() ) {
//            if(dir.isDirectory()) {
//                File[] fileAry = dir.listFiles();
//                if (fileAry != null && fileAry.length > 0) {
//                    for (File innerFile : fileAry) {
//                        if (innerFile.exists() && innerFile.isFile()) {
//                            analyFile(innerFile, libraryDO, maxid);
//                        }
//                    }
//                }
//            }else{
//                if (dir.exists() && dir.isFile()) {
//                    analyFile(dir, libraryDO, maxid);
//                }
//            }
//        }
        if (dir.exists() && dir.isFile()) {
            analyFile(dir, libraryDO, maxid);
        }

    }
public void analyFile(File innerFile, LibraryDO libraryDO,Integer maxid){
    String[] tmpStrAry = innerFile.getName().split("[.]");
    String name = tmpStrAry[0];
    libraryDO.setName(name);
    //  设置排序，可手动更改
    libraryDO.setSortNo(maxid+1);
    int libreturn =  libraryMapper.saveLibraryDO(libraryDO);
    //解析考题,并保存到数据库中，采用事务
    Map<String, Object> map = libraryExcelParser.parseFile(innerFile, libraryDO);
    //更新题目数量
    libraryMapper.updateQuestionNum(libraryDO);

    List<QuestionDO> questionDOList = new ArrayList<QuestionDO>();
    List<AnswerDO> answerDOList = new ArrayList<AnswerDO>();
    questionDOList.addAll((List<QuestionDO>) map.get(APIConstants.QUESTION_LIST));
    answerDOList.addAll((List<AnswerDO>) map.get(APIConstants.ANSWER_LIST));
    //保存考题
    int restbatquestretrun =  bathcInsertQuestionDOList(questionDOList);
    //获取考题数据的MAP
    Map<String, Integer> questionIdMap = getQuestionIdMapbyLibraryId(libraryDO.getId());
    //将答案数据保存到数据库
    int restbathAnswer = batchInsertAnswerDOList(answerDOList, questionIdMap);


    LibQuestionTempDO libQuestionTempDO = new LibQuestionTempDO();
    libQuestionTempDO.setName(innerFile.getName());
    libQuestionTempDO.setLibId(libraryDO.getId());
    libQuestionTempDO.setIndexid(maxid+1);
    //将 libraryDO 存储并返回Id

    int  tempturn = libQuestionTempMapper.insertLibQuestionTemp(libQuestionTempDO);

    if(tempturn < 1){
        throw new ApiException("library存储失败");
    }
    if(libreturn < 1){
        throw new ApiException("library存储失败");
    }
    if(restbatquestretrun < 1){
        throw new ApiException("question存储失败");
    }
    if(restbathAnswer < 1){
        throw new ApiException("answer存储失败");
    }
}
    private Map<String, Integer> getQuestionIdMapbyLibraryId(Integer libraryId) {

        Map<String, Integer> map = new HashMap<String, Integer>();

        //根据LibraryItem.id的集合批量查询QuestionDO的集合
        List<QuestionDO> questionDOList = questionMapper.listQuestionsByLibraryId(libraryId);
        for (QuestionDO questionDO : questionDOList) {
            map.put(questionDO.getUniqueKey(), questionDO.getId());
        }

        return map;
    }


    public int batchInsertAnswerDOList(List<AnswerDO> answerDOList, Map<String, Integer> questionIdMap) {
        //将考题编号与答案关联
        for (AnswerDO answerDO : answerDOList) {
            Integer questionId = questionIdMap.get(answerDO.getUniqueKey());
            answerDO.setQuestionId(questionId);
        }
        //批量保存答案信息
        return insertAnswerDOList(answerDOList);
    }

    public int insertAnswerDOList(List<AnswerDO> answerDOList) {
       return answerMapper.insertAnswerDOList(answerDOList);
    }

    public void removeErrs(String userId,List<AnswerCheck> answerList) {
        for(AnswerCheck answerCheck:answerList) {
            if(answerCheck.isC()) {
                userQuestionErrMapper.deleteByUserIdAndQuestionId(userId,answerCheck.getId());
            }
        }
    }


    public List<QuestionVO> listQuestionVOs(List<UserQuestionErrDO> userQuestionErrDOList) throws ApiException {
        List<Integer> questionIds = null;
        if (CollectionUtils.isNotEmpty(userQuestionErrDOList)) {
            questionIds = new ArrayList<Integer>();
            for (UserQuestionErrDO userQuestionErrDO : userQuestionErrDOList) {
                questionIds.add(userQuestionErrDO.getQuestionId());
            }
        } else {
            throw new ApiException();
        }
        List<QuestionDO> questionDOList =  questionMapper.listQuestionsByIds(questionIds);
        return convertToQuestionVOList(questionDOList);
    }

    public List<QuestionVO> listErrorQuestions(String userId, String time) {
            //1.查看用户是否购买
        List<QuestionVO> questionVOList =null;
            try {
                //1.获取用户所购买课程下专题对应的考题集
                List<UserQuestionErrDO> userQuestionErrDOList = userQuestionErrMapper.listUserQuestionErrsByUserId(userId);

                questionVOList = listQuestionVOs(userQuestionErrDOList);
                List<Integer> questionIds = listQuestionIds(questionVOList);
                //2.获取考题集对应的答案，即对应的选项集
                List<AnswerDO> answerDOList = answerMapper.listAnwsersByQuestionIds(questionIds);
                //3.将Answer的集合封装到对应的考题中
                fillAnswersIntoQuestions(questionVOList, answerDOList);
                if (CollectionUtils.isNotEmpty(questionVOList)) {
                    Collections.sort(questionVOList, new Comparator<QuestionVO>() {
                        @Override
                        public int compare(QuestionVO vo1, QuestionVO vo2) {
                            return vo1.getNo() - vo2.getNo();
                        }
                    });
                }
            } catch (ApiException e) {
            }

            return questionVOList;
    }
}
